package com.runfast.waimai.web.controller.company;

import com.runfast.common.utils.SessionContext;
import com.runfast.common.web.entity.Result;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.RunfastBusinessService;
import com.runfast.waimai.service.WaiMaiRunfastAgentaccountsService;
import com.runfast.waimai.service.WaiMaiRunfastAgentbusinessService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * ${DESCRIPTION}  代理商管理
 *
 * @author chenzheng
 * @create 2018-05-17 17:20
 **/
@RestController("agentController")
@RequestMapping("/server/agent")
public class AgentController {
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Autowired
    private WaiMaiRunfastAgentaccountsService waiMaiRunfastAgentaccountsService;
    @Autowired
    private RunfastBusinessService runfastBusinessService;
    /**
     * 代理商列表带分页的
     */
    @GetMapping("/list")
    public Result list(@PageableDefault Pageable pageable, WaiMaiRunfastAgentbusiness  agentbusiness){
        Map<Object,Object> map1=new HashMap<Object, Object>();
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        WaiMaiRunfastAgentbusinessExample.Criteria exampleCriteria=example.createCriteria();
        if(agentbusiness!=null){
             if(StringUtils.isNotBlank(agentbusiness.getName())){
                 exampleCriteria.andNameLike("%"+agentbusiness.getName()+"%");
                // map1.put("name",agentbusiness.getName());
             }
            /* if(agentbusiness.getAgents().size()>0){
                 exampleCriteria.andIdIn(agentbusiness.getAgents());
             }*/
        }
        exampleCriteria.andFlageNotEqualTo(1);
        map1.put("example",example);
        map1.put("pageable",pageable);
        List<WaiMaiRunfastAgentbusiness> list=waiMaiRunfastAgentbusinessService.selectAgentByExampleWithPageable(map1);
        if(list.size()>0){
            for(WaiMaiRunfastAgentbusiness agentbusiness1:list){
                agentbusiness1.setRname("代理商");
            }
        }
        Integer total=waiMaiRunfastAgentbusinessService.countByExample(example);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("list",list);
        map.put("total",total);
        return Result.ok(null,map);
    }

    /**
     * 代理商列表
     */
    @GetMapping("/select")
    public Result select(){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
        RunfastBusinessAccounts accounts = SessionContext.getRunfastBusinessAccounts();
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        WaiMaiRunfastAgentbusinessExample.Criteria exampleCriteria=example.createCriteria();
        if(admin!=null && admin.getType()==1){
            //后台用户登录返回所有代理商
            if(admin.getAgents().size()>0){
                exampleCriteria.andAgentidIn(admin.getAgents());
            }else{
                //超级管理员所有的
            }
        }else if(admin!=null && admin.getType()==2 && agentAccounts!=null){
            //代理商登录
            WaiMaiRunfastAgentaccounts agentAccounts1= SessionContext.getCurrentRunfastAgentaccounts();
            List<Integer> agents=agentAccounts1.getAgents();//代理商所管的代理商ids
            exampleCriteria.andIdIn(agents);
        }else if(admin!=null && admin.getType()==3 && accounts!=null && accounts.getBusinessid()!=null){
                RunfastBusiness business=runfastBusinessService.selectByPrimaryKey(accounts.getBusinessid());
                if(business!=null && business.getAgentid()!=null){
                    exampleCriteria.andIdEqualTo(business.getAgentid());
                }else{return Result.fail(null,"找不到对应的商家！");}
        }
        List<WaiMaiRunfastAgentbusiness> list = waiMaiRunfastAgentbusinessService.selectByExample(example);
        return Result.ok(null,list);
    }

    /**
     * 代理商信息
     */
    @GetMapping("/info")
    public Result info(Integer id){
        WaiMaiRunfastAgentbusiness agentbusiness=new WaiMaiRunfastAgentbusiness();
        if(id!=null){
            agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(id);
            if(agentbusiness!=null){
                setAgent1(agentbusiness);
                WaiMaiRunfastAgentaccountsExample example=new WaiMaiRunfastAgentaccountsExample();
                example.createCriteria().andAgentidEqualTo(agentbusiness.getId()).andByrolesEqualTo("12");
                List<WaiMaiRunfastAgentaccounts>  agentaccountsList=waiMaiRunfastAgentaccountsService.selectByExample(example);
                if(agentaccountsList.size()>0){
                    agentbusiness.setAccounts(agentaccountsList.get(0).getAccounts());
                }else{return Result.fail(null,"找不对对应的代理商账户信息！");}
            }else{return Result.fail(null,"找不到对应的代理商信息！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null,agentbusiness);
    }
    public void setAgent1(WaiMaiRunfastAgentbusiness agentbusiness){
        if(agentbusiness.getContractStartTime()!=null && agentbusiness.getContractEndTime()!=null){
            List<Date> startTimeToendTime=new ArrayList<Date>();
            startTimeToendTime.add(agentbusiness.getContractStartTime());
            startTimeToendTime.add(agentbusiness.getContractEndTime());
            agentbusiness.setStartTimeToendTime(startTimeToendTime);
        }
    }

    /**
     * 保存代理商
     */
    @PostMapping("/save")
    public Result save(@RequestBody WaiMaiRunfastAgentbusiness  agentbusiness){
        if(agentbusiness!=null && StringUtils.isNotBlank(agentbusiness.getName())&& agentbusiness.getCoefficient()!=null && StringUtils.isNotBlank(agentbusiness.getOfficeAddress())
                && StringUtils.isNotBlank(agentbusiness.getLegalName())&& StringUtils.isNotBlank(agentbusiness.getAccounts()) &&StringUtils.isNotBlank(agentbusiness.getLegalMobile())
                &&StringUtils.isNotBlank(agentbusiness.getLegalIdnumber()) &&StringUtils.isNotBlank(agentbusiness.getCompanyName())&&StringUtils.isNotBlank(agentbusiness.getLegalIdNegativeLoad())
                &&StringUtils.isNotBlank(agentbusiness.getLegalIdPositiveLoad())&& StringUtils.isNotBlank(agentbusiness.getUnifiedSocialCreditCodeLoad())&&StringUtils.isNotBlank(agentbusiness.getAdminName())
                &&StringUtils.isNotBlank(agentbusiness.getAdminMobile())&&agentbusiness.getAdminIdnumber()!=null&&StringUtils.isNotBlank(agentbusiness.getAdminIdNegativeLoad())&& StringUtils.isNotBlank(agentbusiness.getAdminIdPositiveLoad())
                &&StringUtils.isNotBlank(agentbusiness.getPublicAccountsName())&&StringUtils.isNotBlank(agentbusiness.getBankAccount())&&StringUtils.isNotBlank(agentbusiness.getAccountBank())&&
                StringUtils.isNotBlank(agentbusiness.getAccountBankProvinceCity())&& StringUtils.isNotBlank(agentbusiness.getBranchName())&& agentbusiness.getAccountBankLinkBankNo()!=null&&
                agentbusiness.getPayableDeposit()!=null && agentbusiness.getDepositPaid()!=null && agentbusiness.getStartTimeToendTime().size()>0){
                setAgent(agentbusiness);
                WaiMaiRunfastAgentaccounts agentaccounts=new WaiMaiRunfastAgentaccounts();
                agentbusiness.setCreatetime(new Date());
                if(agentbusiness.getAgentid()==null){
                     //公司代理
                    agentbusiness.setAgentid(null);
                    agentbusiness.setFlage(3);
                }else{
                    agentbusiness.setFlage(2);
                    WaiMaiRunfastAgentbusiness  agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentbusiness.getAgentid());
                    if(agentbusiness1!=null){
                        agentbusiness.setAgentid(agentbusiness1.getId());
                        agentbusiness.setAgentname(agentbusiness1.getName());
                    }else{return Result.fail(null,"找不到对应的区域代理！");}
                }
                waiMaiRunfastAgentbusinessService.insertSelective(agentbusiness);

                agentaccounts.setAccounts(agentbusiness.getAccounts());
                agentaccounts.setPassword(DigestUtils.md5Hex("123456"));//默认密码
                agentaccounts.setCreatetime(new Date());
                agentaccounts.setAgentid(agentbusiness.getId());
                agentaccounts.setAgentname(agentbusiness.getName());
                agentaccounts.setByroles("12");
                agentaccounts.setMobile(agentbusiness.getMobile());
                agentaccounts.setName(agentbusiness.getName());
                agentaccounts.setCid(agentbusiness.getCid());
                agentaccounts.setCityname(agentbusiness.getCityname());
                agentaccounts.setPid(agentbusiness.getPid());
                agentaccounts.setProvince(agentbusiness.getProvince());
                agentaccounts.setCountyname(agentbusiness.getCountyname());
                agentaccounts.setTid(agentbusiness.getTid());
                waiMaiRunfastAgentaccountsService.insertSelective(agentaccounts);
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }
    public void setAgent(WaiMaiRunfastAgentbusiness agentbusiness){
        if(agentbusiness.getStartTimeToendTime().size()>0){
            agentbusiness.setContractStartTime(agentbusiness.getStartTimeToendTime().get(0));
            agentbusiness.setContractEndTime(agentbusiness.getStartTimeToendTime().get(1));
        }else{
            agentbusiness.setContractStartTime(null);
            agentbusiness.setContractEndTime(null);
        }
    }

    /**
     * 修改代理商
     */
    @PostMapping("/update")
    public Result update(@RequestBody WaiMaiRunfastAgentbusiness  agentbusiness){
        if(agentbusiness!=null &&agentbusiness.getId()!=null && StringUtils.isNotBlank(agentbusiness.getName())&& agentbusiness.getCoefficient()!=null && StringUtils.isNotBlank(agentbusiness.getOfficeAddress())
                && StringUtils.isNotBlank(agentbusiness.getLegalName())&& StringUtils.isNotBlank(agentbusiness.getAccounts()) &&StringUtils.isNotBlank(agentbusiness.getLegalMobile())
                &&StringUtils.isNotBlank(agentbusiness.getLegalIdnumber()) &&StringUtils.isNotBlank(agentbusiness.getCompanyName())&&StringUtils.isNotBlank(agentbusiness.getLegalIdNegativeLoad())
                &&StringUtils.isNotBlank(agentbusiness.getLegalIdPositiveLoad())&& StringUtils.isNotBlank(agentbusiness.getUnifiedSocialCreditCodeLoad())&&StringUtils.isNotBlank(agentbusiness.getAdminName())
                &&StringUtils.isNotBlank(agentbusiness.getAdminMobile())&&agentbusiness.getAdminIdnumber()!=null&&StringUtils.isNotBlank(agentbusiness.getAdminIdNegativeLoad())&& StringUtils.isNotBlank(agentbusiness.getAdminIdPositiveLoad())
                &&StringUtils.isNotBlank(agentbusiness.getPublicAccountsName())&&StringUtils.isNotBlank(agentbusiness.getBankAccount())&&StringUtils.isNotBlank(agentbusiness.getAccountBank())&&
                StringUtils.isNotBlank(agentbusiness.getAccountBankProvinceCity())&& StringUtils.isNotBlank(agentbusiness.getBranchName())&& agentbusiness.getAccountBankLinkBankNo()!=null&&
                agentbusiness.getPayableDeposit()!=null && agentbusiness.getDepositPaid()!=null && agentbusiness.getStartTimeToendTime().size()>0){
            setAgent(agentbusiness);
            WaiMaiRunfastAgentaccounts agentaccounts=new WaiMaiRunfastAgentaccounts();
            WaiMaiRunfastAgentbusiness  agentbusiness1=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentbusiness.getId());
            if(agentbusiness1!=null){
                if(agentbusiness.getAgentid()==null){
                    //公司代理
                    agentbusiness.setAgentid(null);
                    agentbusiness.setAgentname(null);
                    agentbusiness.setFlage(3);
                }else{
                    agentbusiness.setFlage(2);
                    WaiMaiRunfastAgentbusiness  agentbusiness2=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(agentbusiness.getAgentid());
                    if(agentbusiness2!=null){
                        agentbusiness.setAgentid(agentbusiness2.getId());
                        agentbusiness.setAgentname(agentbusiness2.getName());
                    }else{return Result.fail(null,"找不到对应的区域代理！");}
                }
                WaiMaiRunfastAgentaccountsExample agentaccountsExample=new WaiMaiRunfastAgentaccountsExample();
                agentaccountsExample.createCriteria().andAgentidEqualTo(agentbusiness1.getId()).andByrolesEqualTo("12");
                List<WaiMaiRunfastAgentaccounts> agentaccountsList=waiMaiRunfastAgentaccountsService.selectByExample(agentaccountsExample);
                if(agentaccountsList.size()>0){
                    agentaccounts=agentaccountsList.get(0);
                    agentaccounts.setAccounts(agentbusiness.getAccounts());
                    agentaccounts.setMobile(agentbusiness.getMobile());
                    agentaccounts.setName(agentbusiness.getName());
                    agentaccounts.setCid(agentbusiness.getCid());
                    agentaccounts.setCityname(agentbusiness.getCityname());
                    agentaccounts.setPid(agentbusiness.getPid());
                    agentaccounts.setProvince(agentbusiness.getProvince());
                    agentaccounts.setCountyname(agentbusiness.getCountyname());
                    agentaccounts.setTid(agentbusiness.getTid());
                    waiMaiRunfastAgentaccountsService.updateByPrimaryKeySelective(agentaccounts);
                }else{return Result.fail(null,"找不到对应的代理商账户信息！");}
                waiMaiRunfastAgentbusinessService.updateByPrimaryKeySelective(agentbusiness);
            }else{return Result.fail(null,"找不到对应的代理商！");}
        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
    }



    /**所属上级--区域代理*/
    @GetMapping("selectSuperAgent")
    public Result selectSuperAgent(){
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        example.createCriteria().andAgentidIsNull().andFlageEqualTo(1);
        List<WaiMaiRunfastAgentbusiness> agentbusinessList=waiMaiRunfastAgentbusinessService.selectByExample(example);
        return Result.ok(null,agentbusinessList);
    }

     /**修改密码*/
     @GetMapping("/setPassword")
     public Result setPassword(Integer id,String password){
        if(id!=null && StringUtils.isNotBlank(password)){
            WaiMaiRunfastAgentbusiness  agentbusiness=waiMaiRunfastAgentbusinessService.selectByPrimaryKey(id);
            if(agentbusiness!=null){
                WaiMaiRunfastAgentaccountsExample example=new WaiMaiRunfastAgentaccountsExample();
                example.createCriteria().andAgentidEqualTo(agentbusiness.getId()).andByrolesEqualTo("12");
                List<WaiMaiRunfastAgentaccounts> agentaccountsList=waiMaiRunfastAgentaccountsService.selectByExample(example);
                if(agentaccountsList.size()>0){
                    WaiMaiRunfastAgentaccounts  agentaccounts=agentaccountsList.get(0);
                    agentaccounts.setPassword(password);
                    waiMaiRunfastAgentaccountsService.updateByPrimaryKeySelective(agentaccounts);
                }
            }else{return Result.fail(null,"找不到对应的代理商！");}

        }else{return Result.fail(null,"传入参数不对！");}
        return Result.ok(null);
     }



    /*** 区域代理：代理商列表*/
    @GetMapping("/AreaSelect")
    public Result AreaSelect(){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        WaiMaiRunfastAgentbusinessExample.Criteria exampleCriteria=example.createCriteria();
        if(admin!=null && admin.getType()==1){
            //后台用户登录返回所有代理商
            exampleCriteria.andFlageEqualTo(3);
        }else{return Result.fail(null,"只有后台才有此权限！");}
        List<WaiMaiRunfastAgentbusiness> list = waiMaiRunfastAgentbusinessService.selectByExample(example);
        return Result.ok(null,list);
    }
    /*** 城市经理：代理商列表*/
    @GetMapping("/citySelect")
    public Result citySelect(){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        WaiMaiRunfastAgentbusinessExample.Criteria exampleCriteria=example.createCriteria();
        if(admin!=null && admin.getType()==1){
            //后台用户登录返回所有代理商
            exampleCriteria.andFlageNotEqualTo(1);
        }else{return Result.fail(null,"只有后台才有此权限！");}
        List<WaiMaiRunfastAgentbusiness> list = waiMaiRunfastAgentbusinessService.selectByExample(example);
        return Result.ok(null,list);
    }

     /**
      * 删除代理商---暂时不实现
     */
    /*@PostMapping("/delete")
    @RequiresPermissions("sys:role:delete")
    public R delete(@RequestBody Long[] roleIds){
        sysRoleService.deleteBatch(roleIds);

        return R.ok();
    }*/

    /**
     * 代理商列表--带分页
     */
   /* @GetMapping("/selectList")
    public Result selectList(@PageableDefault Pageable pageable,WaiMaiRunfastAgentbusiness  agentbusiness){
        BaseUser admin = SessionContext.getAdmin();
        WaiMaiRunfastAgentbusinessExample example=new WaiMaiRunfastAgentbusinessExample();
        WaiMaiRunfastAgentbusinessExample.Criteria exampleCriteria=example.createCriteria();
        if(admin!=null && admin.getType()==1){
            //后台用户登录返回所有代理商.
            if(admin.getAgents().size()>0){
                exampleCriteria.andAgentidIn(admin.getAgents());
            }else{

            }
        }else if(admin.getType()==2){
            //代理商登录
            WaiMaiRunfastAgentaccounts agentAccounts= SessionContext.getCurrentRunfastAgentaccounts();
            List<Integer> agents=agentAccounts.getAgents();//代理商所管的代理商ids
            exampleCriteria.andAgentidIn(agents);
        }

        List<WaiMaiRunfastAgentbusiness> list = waiMaiRunfastAgentbusinessService.selectByExampleWithPageable(example,pageable);
        Integer total=waiMaiRunfastAgentbusinessService.countByExample(example);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("",);
        map.put("",);
        return Result.ok(null,list);
    }*/
}
